<template>
  <div class="day-activeness">
    <!-- 页面主体 -->
    <v-main>
      <!-- 店铺数据总览 -->
      <div class="day-activeness-summary">
        <div class="store-summary">
          <div class="summary-title clearfix">
            <div class="name">
              <span class="pageName">活跃天数</span>
            </div>
          </div>
          <el-row class="summary-main clearfix">
            <el-col :span="8" style="margin-right:20px;">
              <el-date-picker :clearable="false"
                              v-model="choosenDate"
                              type="daterange"
                              size="small"
                              value-format="yyyy-MM-dd"
                              @change = "changeDateRange"
                              :picker-options="pickerOptions"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期">
              </el-date-picker>
              <!-- <el-date-picker :clearable="false"
                              v-show="activeTabsName === 'month'"
                              v-model="monthRange"
                              type="daterange"
                              size="small"
                              value-format="yyyy-MM-dd"
                              @change = "changeMonthRange"
                              :picker-options="pickerOptionsOfMonth"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期">
              </el-date-picker> -->
            </el-col>
          </el-row>
        </div>
      </div>
      <!-- 店铺图标 tabs -->
      <div class="compass-tabs">
        <el-tabs v-model="activeTabsName">
          <!-- tab - 新增顾客 -->
          <el-tab-pane label="周活跃构成" name="week">
            <div class="customer-number-view data-view">
              <div class="panel-title">
                <span>趋势图</span>
              </div>
              <div class="panel-charts">
                <v-echarts :options="WOAChartsOption"></v-echarts>
              </div>
              <div class="panel-title">
                <span>顾客周活跃构成明细</span>
                <span class="save-csv-link" @click="saveDataToDesktop">
                  <i class="iconfont">&#xe68e;</i>
                  导出CSV</span>
              </div>
              <div class="panel-table">
                <el-table :data="currTableDataOfWeek"
                          border
                          size="small"
                          highlight-current-row
                          style="width: 100%">
                  <el-table-column prop="week"
                                   label="时间"
                                   align="center"
                                   sortable
                                   width="180">
                  </el-table-column>
                  <el-table-column prop="week_1"
                                   align="center"
                                   sortable
                                   label="活跃1周">
                    <template slot-scope="scope">{{ scope.row.week_1 !== null && scope.row.week_1 !== undefined ? scope.row.week_1 : 0 }}</template>
                  </el-table-column>
                  <el-table-column prop="week_2"
                                   align="center"
                                   sortable
                                   label="活跃2周">
                    <template slot-scope="scope">{{ scope.row.week_2 !== null && scope.row.week_2 !== undefined ? scope.row.week_2 : 0 }}</template>
                  </el-table-column>
                  <el-table-column prop="week_3"
                                   align="center"
                                   sortable
                                   label="活跃3周">
                    <template slot-scope="scope">{{ scope.row.week_3 !== null && scope.row.week_3 !== undefined ? scope.row.week_3 : 0 }}</template>
                  </el-table-column>
                  <el-table-column prop="week_4"
                                   align="center"
                                   sortable
                                   label="活跃4周">
                    <template slot-scope="scope">{{ scope.row.week_4 !== null && scope.row.week_4 !== undefined ? scope.row.week_4 : 0 }}</template>
                  </el-table-column>
                  <el-table-column prop="week_5"
                                   align="center"
                                   sortable
                                   label="活跃5周">
                    <template slot-scope="scope">{{ scope.row.week_5 !== null && scope.row.week_5 !== undefined ? scope.row.week_5 : 0 }}</template>
                  </el-table-column>
                  <el-table-column prop="week_6"
                                   align="center"
                                   sortable
                                   label="活跃6周">
                    <template slot-scope="scope">{{ scope.row.week_6 !== null && scope.row.week_6 !== undefined ? scope.row.week_6 : 0 }}</template>
                  </el-table-column>
                  <el-table-column prop="week_7"
                                   align="center"
                                   sortable
                                   label="活跃7周">
                    <template slot-scope="scope">{{ scope.row.week_7 !== null && scope.row.week_7 !== undefined ? scope.row.week_7 : 0 }}</template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
          <!-- tab - 进店人数 -->
          <el-tab-pane label="月活跃构成" name="month">
            <div class="customer-number-view data-view">
              <div class="panel-title">
                <span>趋势图</span>
              </div>
              <div class="panel-charts">
                <v-echarts :options="MOAChartsOption"></v-echarts>
              </div>
              <div class="panel-title">
                <span>顾客月活跃构成明细</span>
                <span class="save-csv-link" @click="saveDataToDesktop">
                  <i class="iconfont">&#xe68e;</i>
                  导出CSV</span>
              </div>
              <div class="panel-table">
                <el-table :data="currTableDataOfMonth"
                          border
                          size="small"
                          highlight-current-row
                          style="width: 100%">
                  <el-table-column prop="stats_date"
                                   label="时间"
                                   align="center"
                                   sortable
                                   width="180">
                  </el-table-column>
                  <el-table-column prop="month_1"
                                   align="center"
                                   sortable
                                   label="活跃1月">
                    <template slot-scope="scope">{{ scope.row.month_1 !== null && scope.row.month_1 !== undefined ? scope.row.month_1 : 0 }}</template>
                  </el-table-column>
                  <el-table-column prop="month_2"
                                   align="center"
                                   sortable
                                   label="活跃2月">
                    <template slot-scope="scope">{{ scope.row.month_2 !== null && scope.row.month_2 !== undefined ? scope.row.month_2 : 0 }}</template>
                  </el-table-column>
                  <el-table-column prop="month_3"
                                   align="center"
                                   sortable
                                   label="活跃3月">
                    <template slot-scope="scope">{{ scope.row.month_3 !== null && scope.row.month_3 !== undefined ? scope.row.month_3 : 0 }}</template>
                  </el-table-column>
                  <el-table-column prop="month_4"
                                   align="center"
                                   sortable
                                   label="活跃4月">
                    <template slot-scope="scope">{{ scope.row.month_4 !== null && scope.row.month_4 !== undefined ? scope.row.month_4 : 0.00 }}</template>
                  </el-table-column>
                  <el-table-column prop="month_5"
                                   align="center"
                                   sortable
                                   label="活跃5月">
                    <template slot-scope="scope">{{ scope.row.month_5 !== null && scope.row.month_5 !== undefined ? scope.row.month_5 : 0.00}}</template>
                  </el-table-column>
                  <el-table-column prop="month_6"
                                   align="center"
                                   sortable
                                   label="活跃6月">
                    <template slot-scope="scope">{{ scope.row.month_6 !== null && scope.row.month_6 !== undefined ? scope.row.month_6 : 0.00}}</template>
                  </el-table-column>

                  <el-table-column prop="month_7"
                                   align="center"
                                   sortable
                                   label="活跃7月">
                    <template slot-scope="scope">{{ scope.row.month_7 !== null && scope.row.month_7 !== undefined ? scope.row.month_7 : 0.00}}</template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </v-main>
  </div>
</template>
<script type="text/ecmascript-6">
import { mapGetters } from 'vuex'
// components
import MainComp from '@/components/main'
import EchartComp from '@/components/echarts'
// 图标的配置文件
import weekActivenessEchartOption from './weekActivenessEchartOption.js'
import monthActivenessEchartOption from './monthActivenessEchartOption.js'

// element-ui
import { Row, Col, DatePicker, Tabs, TabPane, Table, TableColumn } from 'element-ui'
/**
 * Parse, validate, manipulate, and display dates in javascript
 * @Documents http://momentjs.com/
 */
import Moment from 'moment'
import { APIGetWeekOfLivenessData, APIGetMonthOfLivenessData } from '@/api/customerSticky.js'
import Config from '@/utils/config.js'

export default {
  name: 'dayOfActiveness',

  components: {
    // elementUI component
    elRow: Row,
    elCol: Col,
    elDatePicker: DatePicker,
    elTabs: Tabs,
    elTabPane: TabPane,
    elTable: Table,
    elTableColumn: TableColumn,
    // 项目自定义组件
    vMain: MainComp,
    vEcharts: EchartComp
  },

  created () {
    // init request
    this.APIGetWeekOfLivenessData(this.dateRangeOfWeek)
    this.APIGetMonthOfLivenessData(this.dateRangeOfMonth)
  },

  data () {
    return {
      // default tab name
      activeTabsName: 'week',
      // echarts option
      WOAChartsOption: {},
      MOAChartsOption: {},
      // 用户所选时间 Number(Moment().format('E'))  获取今天的每周的第几天
      choosenDate: [Moment().subtract(Number(Moment().format('E')), 'day').subtract(13, 'day').format('YYYY-MM-DD'), Moment().subtract(Number(Moment().format('E')), 'day').format('YYYY-MM-DD')],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Moment().subtract(Number(Moment().format('E')), 'day')
        },
        firstDayOfWeek: 1
      },
      // monthRange: [Moment().subtract(Number(Moment().format('E')), 'day').subtract(13, 'day').format('YYYY-MM-DD'), Moment().subtract(Number(Moment().format('E')), 'day').format('YYYY-MM-DD')],
      // pickerOptionsOfMonth: {
      //   disabledDate (time) {
      //     return time.getTime() > Moment().subtract(Number(Moment().format('E')), 'day')
      //   },
      //   firstDayOfWeek: 1
      // },
      // 表格数据
      WOAData: [],
      MOAData: [],
      sunday: [],
      totalNumOfWeek: [],
      totalNumOfMonth: []
    }
  },

  computed: {
    ...mapGetters([
      'mallId',
      'token'
    ]),
    currTableDataOfWeek () {
      return this.WOAData || []
    },
    currTableDataOfMonth () {
      return this.MOAData || []
    },
    dateRangeOfWeek () {
      let startDate = Moment(this.choosenDate[0]).subtract(Number(Moment(this.choosenDate[0]).format('E')) - 1, 'day').format('YYYY-MM-DD')
      let endDate = Moment(this.choosenDate[1]).add(7 - Number(Moment(this.choosenDate[1]).format('E')), 'day').format('YYYY-MM-DD')
      return [startDate, endDate]
    },
    dateRangeOfMonth () {
      const currMonth = Moment().format('YYYY-MM')
      const dateRange = this.choosenDate
      //  a,b 代表的是在相对的时间范围里面 返回的 应该减去的月份值
      let [startDate, endDate, a, b] = ['', '', '', '']
      if (Moment(dateRange[0]).format('YYYY-MM') === currMonth &&
      Moment(dateRange[1]).format('YYYY-MM') === currMonth) {
        a = 1
        b = 1
      } else if (Moment(dateRange[1]).format('YYYY-MM') === currMonth) {
        a = 0
        b = 1
      } else {
        a = 0
        b = 0
      }
      startDate = Moment(dateRange[0]).subtract(a, 'month').format('YYYY-MM')
      endDate = Moment(dateRange[1]).subtract(b, 'month').format('YYYY-MM')
      return [startDate, endDate]
    },
    xAxisOfWeekCharts () {
      let data = []
      for (let i = 1; i < 8; i++) {
        data.unshift(`活跃${i}周`)
      }
      return data
    },
    xAxisOfMonthCharts () {
      let data = []
      for (let i = 1; i < 8; i++) {
        data.unshift(`活跃${i}月`)
      }
      return data
    }
  },

  methods: {
    saveDataToDesktop () {
      if (this.activeTabsName === 'week') {
        window.location.href = `${Config.CURR_REQ_URL}/api/shops/${this.mallId}/liveness-list/export?api_token=${this.token}&start_date=${this.dateRangeOfWeek[0]}&end_date=${this.dateRangeOfWeek[1]}&type=${this.activeTabsName}`
      } else {
        window.location.href = `${Config.CURR_REQ_URL}/api/shops/${this.mallId}/liveness-list/export?api_token=${this.token}&start_date=${this.dateRangeOfMonth[0]}&end_date=${this.dateRangeOfMonth[1]}&type=${this.activeTabsName}`
      }
    },
    // 日期选择器
    changeDateRange () {
      this.APIGetWeekOfLivenessData(this.dateRangeOfWeek)
      this.APIGetMonthOfLivenessData(this.dateRangeOfMonth)
    },
    // 设置echartsOption
    setWOAChartsOption () {
      const base = {
        title: {
          text: '顾客周活跃构成',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            //  自定义每周周日属性
            let sunday = this.sunday[params[0]['dataIndex']]
            let sum = this.totalNumOfWeek[params[0]['dataIndex']]
            let res = ''
            for (let i = params.length - 1; i >= 0; i--) {
              let value = params[i].value
              let color = params[i].color
              let radio = isNaN(Math.round(value / sum * 10000) / 100) ? 0 : (Math.round(value / sum * 10000) / 100)
              let seriesName = params[i]['seriesName']
              res += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + color + '"></span>' +
                seriesName + ': ' + value + ` (${radio}%)` + '</br>'
            }
            res = `${params[0]['axisValue']}至${sunday}` + '</br>' + res
            return res
          }
        }
      }
      const series = {
        type: 'bar',
        stack: '总量',
        barMaxWidth: '20'
      }
      const WOAchartsData = this.WOAData || []
      let option = Object.assign({}, weekActivenessEchartOption, base)
      let data = [].concat(...WOAchartsData).reverse()
      option.xAxis = Object.assign({}, option.xAxis, { data: data.map(item => item.week_monday) })
      let seriesData = []
      for (let i = 0; i < 7; i++) {
        seriesData.unshift(Object.assign({}, series, {name: this.xAxisOfWeekCharts[i]}, {data: data.map(item => item[`week_${7 - i}`])}))
      }
      // 增加自定义属性 周末日期 以及 合计
      this.sunday = data.map(item => item.week_sunday)
      this.totalNumOfWeek = data.map(item => item.total_num)
      option.series = seriesData
      this.WOAChartsOption = option
    },
    setMOAChartsOption () {
      const base = {
        title: {
          text: '顾客月活跃构成',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            //  自定义 每月合计数
            let sum = this.totalNumOfMonth[params[0]['dataIndex']]
            let res = ''
            for (let i = params.length - 1; i >= 0; i--) {
              let value = params[i].value
              let color = params[i].color
              let radio = isNaN(Math.round(value / sum * 10000) / 100) ? 0 : (Math.round(value / sum * 10000) / 100)
              let seriesName = params[i]['seriesName']
              res += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' + color + '"></span>' +
                seriesName + ': ' + value + ` (${radio}%)` + '</br>'
            }
            res = params[0]['axisValue'] + '</br>' + res
            return res
          }
        }
      }
      const series = {
        type: 'bar',
        stack: '总量',
        barMaxWidth: '20'
      }
      const MOAchartsData = this.MOAData || []
      let option = Object.assign({}, monthActivenessEchartOption, base)
      let seriesData = []
      let data = [].concat(...MOAchartsData).reverse()
      option.xAxis = Object.assign({}, option.xAxis, { data: data.map(item => item.stats_date) })
      for (let i = 0; i < 7; i++) {
        seriesData.unshift(Object.assign({}, series, {name: this.xAxisOfMonthCharts[i]}, {data: data.map(item => item[`month_${7 - i}`])}))
      }
      // 增加自定义属性合计
      this.totalNumOfMonth = data.map(item => item.total_num)
      option.series = seriesData
      this.MOAChartsOption = option
    },
    // ======= API ==================
    APIGetWeekOfLivenessData (dateRangeOfWeek) {
      let startDate = dateRangeOfWeek[0]
      let endDate = dateRangeOfWeek[1]
      APIGetWeekOfLivenessData({ shop: this.mallId, startDate, endDate })
        .then((res) => {
          let data = res.data.stats.list
          data.forEach((item) => { item.week = `${item.week_monday}~${item.week_sunday}` })
          this.WOAData = data
          this.setWOAChartsOption()
        })
    },
    APIGetMonthOfLivenessData (dateRangeOfMonth) {
      let startDate = dateRangeOfMonth[0]
      let endDate = dateRangeOfMonth[1]
      APIGetMonthOfLivenessData({ shop: this.mallId, startDate, endDate })
        .then((res) => {
          this.MOAData = res.data.stats.list
          this.setMOAChartsOption()
        })
    }
  }
}
</script>

<style lang="less" rel="stylesheet/less">
  // scoped
  .day-activeness {
    .day-activeness-summary {
      width: 100%;
      height: auto;
      box-sizing: border-box;
      background-color: #FFF;
      padding: 10px 20px;
      box-shadow: 0 2px 3px 0 rgba(0, 0, 0, .2);
      .summary-title {
        padding: 10px 0;
        height: 30px;
        line-height: 30px;
        border-bottom: 1px solid #DFDFDF;
        overflow: hidden;
        .name {
          float: left;
          font-weight: bold;
          font-size: 18px;
        }
        .date {
          float: left;
          margin-left: 30px;
          color: #777;
          font-size: 14px;
        }
      }
      .summary-main {
        margin-top: 10px;
        padding: 10px;
        .summary-wrapper {
          float: left;
          margin-left: 2%;
          width: 18.4%;
          &:first-child {
            margin-left: 0;
          }
          .summary-item {
            box-sizing: border-box;
            padding: 20px;
            width: 100%;
            background-color: #FFF;
            border: 1px solid #DFDFDF;
            .label {
              color: #777;
              font-size: 14px;
              .iconfont {
                margin-left: 5px;
              }
            }
            .value {
              padding: 5px 0;
              margin-top: 10px;
              font-size: 32px;
              line-height: 32px;
            }
            .desc {
              font-size: 14px;
              margin-top: 10px;
              .num {
                &.rise {
                  color: #E64340;
                }
                &.fall {
                  color: #45C01A;
                }
              }
              .mom {
                font-size: 14px;
                margin-top: 10px;
                &.rise {
                  color: #E64340;
                }
                &.fall {
                  color: #45C01A;
                }
              }
            }
          }
        }
      }
    }
    .compass-tabs {
      box-sizing: border-box;
      margin-top: 20px;
      padding: 10px 20px;
      width: 100;
      background-color: #FFF;
      box-shadow: 0 2px 3px 0 rgba(0, 0, 0, .2);
      .el-tabs__content {
        // 修改table 组件样式  tooltip显示问题
        overflow: visible;
      }
      .data-view {
        .panel-title {
          font-size: 16px;
          .instructions {
            color: #777;
          }
          .save-csv-link {
            float: right;
            cursor: pointer;
            font-size: 13px;
            color: #0269c8;
          }
        }
        .panel-charts {
          padding: 20px 0;
          width: 100%;
          height: 350px;
        }
        .panel-table {
          padding: 20px 0;
          width: 100%;
        }
      }
    }
  }
</style>
